package org.pzy.java.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: DRevelation
 * @Date: 2022/6/17 10:33
 */
public class JacksonDemo {
    public static void main(String[] args) throws JsonProcessingException {

        List<String> books = new ArrayList<>();
        books.add("Java");
        books.add("Go");
        User user = User.builder().id(1).name("abc").email("abc@123.com").books(books).other(123L).build();

        ObjectMapper mapper = new ObjectMapper();
        String jackson = mapper.writeValueAsString(user);
        System.out.println("jackson = " + jackson);

        User user1 = mapper.readValue(jackson, User.class);
        System.out.println("user1 = " + user1);

        JsonNode jsonNode = mapper.readTree(jackson);

        // path get 基本相同 获取下层JsonNode, asXXX()获取当前值
        System.out.println("name = " + jsonNode.path("name").asText());
        System.out.println("name = " + jsonNode.get("name"));

        JsonNode books1 = jsonNode.get("books");
        System.out.println("books1 = " + books1);
        System.out.println("books1[0] = " + books1.get(0).asText());

    }
}
